import { _decorator, Component, instantiate, macro, Node, Prefab, Script } from 'cc';
import { AssetsManager } from './manager/assets-manager';
import { Pipe } from './Pipe';
const { ccclass, property } = _decorator;

/**
 * 脚本组件默认不启动，等资源加载结束再启动
 */
@ccclass('PipeCtrl')
export class PipeCtrl extends Component {

    private _ctrl: boolean = false
    private createRate: number = 1
    private pipePrefab: Prefab

    onLoad() {
        this.schedule(this.createPipe, this.createRate, macro.REPEAT_FOREVER, 0.5)
        // this.schedule(this.createPipe, this.createRate, 1, 0.5)
        this.pipePrefab = AssetsManager.instance.getAsset('UIStart') as Prefab
    }

    startGame() {
        this._ctrl = true
    }

    stopGame() {
        this._ctrl = false

        // 管道全部停止移动
        const pipes = this.node.children
        pipes.forEach(pipe => pipe.getComponent(Pipe).enabled = false)
    }

    resetGame() {
        // 重置游戏时，管道全部倒退，并销毁
        const pipes = this.node.children
        pipes.forEach((pipe, index) => {
            const pipeScript = pipe.getComponent(Pipe)
            pipeScript.enabled = false
            pipeScript.moveBack(index)
        })
    }

    createPipe() {
        if (!this._ctrl) return
        
        if (!this.pipePrefab) this.pipePrefab = AssetsManager.instance.getAsset('pipe') as Prefab
        
        const pipe = instantiate(this.pipePrefab)
        this.node.addChild(pipe)
    }
}


